<?php

global $_GPC;
global $_W;
$cfg = $this->module['config'];
$shopid = $_GPC['shopid'];
$userid = $_GPC['juserid'];
if (!$userid || !$shopid) {
    $operation = 'login';
    if ($_GPC['screen']) {
        include $this->template($cfg['floder'] . '/phone/phone2');
    } else {
        include $this->template($cfg['floder'] . '/phone/phone');
    }
    exit(0);
}
$userOper = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_user') . ' WHERE weid=\'' . $_W['uniacid'] . '\' and id=:a limit 1', array(':a' => $userid));
if (!$userOper) {
    message('用户不存在或者密码错误', $this->createMobileUrl('phone', array('op' => 'login')), 'error');
}
if (!$userOper['status']) {
    message('该用户还没有审核，请联系管理员', $this->createMobileUrl('phone', array('op' => 'login')), 'error');
}
$shopid = $userOper['pcate'];
$shop = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_group') . ' WHERE id =:a', array(':a' => $shopid));
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
load()->model('mc');
if ($operation == 'display') {
    $tablepcatelist = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_tablecategory') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and groupid =\'' . $shopid . '\' order by displayorder asc,id desc');
    $categoryary = array();
    foreach ($tablepcatelist as $row) {
        $categoryary[$row['id']] = $row['title'];
    }
    $goodpcatelist = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_goodcategory') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and groupid =\'' . $shopid . '\' order by  displayorder asc, id desc');
    $isNoPcate = pdo_fetchcolumn('SELECT count(*) FROM ' . tablename('j_hmoney_goods') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and groupid =\'' . $shopid . '\' and pcate=0');
    $isfungood = pdo_fetchcolumn('SELECT count(*) FROM ' . tablename('j_hmoney_goodmarket') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and groupid =\'' . $shopid . '\' and status=1 and starttime<=\'' . TIMESTAMP . '\' and endtime>=\'' . TIMESTAMP . '\' and contentid<>\'\' ');
} else {
    if ($operation == 'logout') {
        isetcookie('juserid', '', -1);
        isetcookie('shopid', '', -1);
        isetcookie('shortpass', '', -1);
        isetcookie('selfttableid', '', -1);
        exit(json_encode(array('success' => true)));
    } else {
        if ($operation == 'startorder') {
            $tid = intval($_GPC['tid']);
            $person = intval($_GPC['person']);
            if (!$tid) {
                exit(json_encode(array('success' => false, 'msg' => '请选择餐桌')));
            }
            $table = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_table') . ' WHERE id=:a ', array(':a' => $tid));
            isetcookie('selfttableid', $tid);
            if ($table['status'] == 0) {
                $hasOldorder = pdo_fetchcolumn('SELECT count(*) FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and tabile=:a and ispay=0 ', array(':a' => $trade['tableid'], ':b' => $orderid));
                if ($hasOldorder) {
                    exit($_GET['callback'] . '(' . json_encode(array('success' => false, 'msg' => '该餐桌还有订单未处理，请先处理该订单')) . ')');
                }
                $orderDisplayorder = pdo_fetchcolumn('SELECT max(serialnum) FROM ' . tablename('j_hmoney_order') . ' WHERE weid=\'' . $_W['uniacid'] . '\' and groupid=:a and createdate=:b ', array(':a' => $tid, ':b' => date('Y-m-d')));
                $data = array('weid' => $_W['uniacid'], 'groupid' => $shopid, 'userid' => $userid, 'serialnum' => $orderDisplayorder + 1, 'out_trade_no' => TIMESTAMP . mt_rand(100, 999), 'tableid' => $tid, 'person' => $person, 'teafee' => intval(($person * $table['perperson'] + $table['teafee']) * 100), 'createtime' => TIMESTAMP, 'createdate' => date('Y-m-d'), 'createterminal' => 2);
                pdo_insert('j_hmoney_order', $data);
                $orderid = pdo_insertid();
                pdo_update('j_hmoney_table', array('status' => 1, 'createtime' => TIMESTAMP), array('id' => $tid));
                $trade = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and id=:a ', array(':a' => $orderid));
                exit(json_encode(array('success' => true, 'table' => $table, 'trade' => $trade)));
            } else {
                if ($table['status'] == 1) {
                    $trade = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and tableid=:a order by id desc limit 1', array(':a' => $tid));
                    if ($orderid) {
                        $trade = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and id=:a ', array(':a' => $orderid));
                    }
                    $goodlist = pdo_fetchall('SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice FROM ' . tablename('j_hmoney_ordergoods') . ' as a LEFT JOIN ' . tablename('j_hmoney_goods') . ' as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ', array(':a' => $trade['out_trade_no']));
                    exit(json_encode(array('success' => true, 'table' => $table, 'trade' => $trade, 'goods' => $goodlist)));
                } else {
                    if ($table['status'] == 2) {
                        $tradelist = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and tableid=:a and status<2 order by id desc  ', array(':a' => $tid));
                        if (count($tradelist) == 1) {
                            $trade = $tradelist[0];
                            $goodlist = pdo_fetchall('SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice FROM ' . tablename('j_hmoney_ordergoods') . ' as a LEFT JOIN ' . tablename('j_hmoney_goods') . ' as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ', array(':a' => $trade['out_trade_no']));
                            exit(json_encode(array('success' => true, 'table' => $table, 'trade' => $trade, 'goods' => $goodlist)));
                        } else {
                            exit(json_encode(array('success' => true, 'table' => $table, 'tradelist' => $tradelist)));
                        }
                    }
                }
            }
            exit(json_encode(array('success' => true)));
        } else {
            if ($operation == 'getpcatetable') {
                $pcate = intval($_GPC['pcate']);
                if (!$pcate) {
                    $pcate = pdo_fetchcolumn('SELECT id FROM ' . tablename('j_hmoney_tablecategory') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and groupid =\'' . $shopid . '\' order by displayorder asc,id desc limit 1');
                }
                $tablelist = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_table') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and pcate=:a order by status desc ,displayorder asc,id asc', array(':a' => $pcate));
                exit(json_encode(array('success' => true, 'list' => $tablelist)));
            } else {
                if ($operation == 'getpcategood') {
                    $pcate = intval($_GPC['pcate']);
                    $goodslist = array();
                    if ($pcate == -1) {
                        $list = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_goodmarket') . ' WHERE groupid=:a and status=1 and starttime<=:b and endtime>=:b and contentid<>\'\' order by id desc', array(':a' => $shopid, ':b' => TIMESTAMP));
                        foreach ($list as $row) {
                            if ($row['limitweek']) {
                                $day = date('w') ? date('w') : 7;
                                if (!in_array($day, explode(',', $row['limitweek']))) {
                                    continue;
                                } else {
                                    if ($row['limithour']) {
                                        $time = intval(date('h'));
                                        if (!in_array($time, explode(',', $row['limithour']))) {
                                            continue;
                                        } else {
                                            $goods = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_goods') . ' WHERE id in(' . $row['contentid'] . ') and status=1 and store<>0 order by id desc');
                                            $i = 0;
                                            while ($i < count($goods)) {
                                                $temp = $goods[$i];
                                                if (strpos($row['discount'], '%')) {
                                                    $temp['title2'] = str_replace('%', '', $row['discount']) * 0 . '折';
                                                    str_replace('%', '', $row['discount']);
                                                    $temp['marketprice'] = $this->_2money($goods[$i]['marketprice'] * str_replace('%', '', $row['discount']));
                                                }
                                                if (strpos($row['discount'], '-') !== false) {
                                                    abs($row['discount']);
                                                    if ($goods[$i]['marketprice'] - abs($row['discount']) >= 0) {
                                                        $temp['title2'] = str_replace('-', '立减', $row['discount']);
                                                        abs($row['discount']);
                                                        $temp['marketprice'] = $this->_2money(($goods[$i]['marketprice'] - abs($row['discount'])) * 100);
                                                    }
                                                }
                                                array_push($goodslist, $temp);
                                                $i = $i + 1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        $goodslist = pdo_fetchall('SELECT * FROM ' . tablename('j_hmoney_goods') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and pcate=:a and groupid=:b and status=1 and store<>0 order by displayorder asc,id asc', array(':a' => $pcate, ':b' => $shopid));
                    }
                    $i = 0;
                    while ($i < count($goodslist)) {
                        if ($goodslist[$i]['thumb']) {
                            $goodslist[$i]['thumb'] = tomedia($goodslist[$i]['thumb']);
                        }
                        $i = $i + 1;
                    }
                    exit(json_encode(array('success' => true, 'list' => $goodslist, 'a' => count($goods))));
                } else {
                    if ($operation == 'submitorder') {
                        $orderid = $_GPC['orderid'];
                        $person = $_GPC['person'];
                        $param = $_GPC['param'];
                        if (!$orderid) {
                            exit(json_encode(array('success' => false, 'msg' => '订单编号不能为空')));
                        }
                        $trade = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_order') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and id=:a ', array(':a' => $orderid));
                        $table = pdo_fetch('SELECT * FROM ' . tablename('j_hmoney_table') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and id=:a ', array(':a' => $trade['tableid']));
                        $sqlinsert = 'insert into ' . tablename('j_hmoney_ordergoods') . ' (weid,groupid,orderid,out_trade_no,createtime,status,goodid,goodsn,title,price,oldprice,num,total_fee,ispack,taste)VALUES';
                        $newgoodAry = array();
                        $tempInsertAry = array();
                        $isallnew = true;
                        foreach ($param as $row) {
                            $tempAry = explode('|', $row);
                            if (!$tempAry[0]) {
                                if (!isset($newgoodAry[$tempAryb])) {
                                    $newgoodAry[$tempAry[1]] = 0;
                                }
                                $newgoodAry[$tempAry[1]] = $newgoodAry[$tempAry[1]] + $tempAry[7];
                                intval($tempAry[8] * 100);
                                intval($tempAry[9]);
                                $temp = array(0 => $_W['uniacid'], 1 => $shopid, 2 => $orderid, 3 => $trade['out_trade_no'], 4 => TIMESTAMP, 5 => 1, 6 => $tempAry[1], 7 => $tempAry[2], 8 => $tempAry[3], 9 => $tempAry[4], 10 => $tempAry[6], 11 => $tempAry[7], 12 => intval($tempAry[8] * 100), 13 => intval($tempAry[9]), 14 => $tempAry[10]);
                                $tempInsertAry[] = '(\'' . implode('\',\'', $temp) . '\')';
                            } else {
                                $isallnew = false;
                                $temp = array('price' => $tempAry[4], 'fee' => intval($tempAry[8] * 100), 'ispack' => $tempAry[9], 'taste' => $tempAry[10]);
                                pdo_update('j_hmoney_ordergoods', $temp, array('id' => $tempAry[0]));
                            }
                        }
                        if (count($newgoodAry)) {
                            $goodataAry = array();
                            $goodsql = 'UPDATE ' . tablename('j_hmoney_goods') . ' SET store = CASE id ';
                            $goodlist = pdo_fetchall('SELECT id,store,title FROM ' . tablename('j_hmoney_goods') . ' WHERE id in (' . implode(',', array_keys($newgoodAry)) . ') and store>-1 ');
                            foreach ($goodlist as $row) {
                                if ($row['store'] - $newgoodAry[$row['id']] < 0) {
                                    exit(json_encode(array('success' => false, 'msg' => '【' . $row['title'] . '】库存不足,差【' . abs($row['store'] - $newgoodAry[$row['id']]) . '】份')));
                                } else {
                                    $goodsql .= ' WHEN ' . $row['id'] . ' THEN ' . ($row['store'] - $newgoodAry[$row['id']]);
                                    continue;
                                }
                            }
                            $goodsql .= 'END WHERE id IN (' . implode(',', array_keys($newgoodAry)) . ')';
                            $sql = $sqlinsert . implode(',', $tempInsertAry) . ';' . $goodsql;
                            pdo_run($sql);
                        }
                        pdo_update('j_hmoney_table', array('status' => 2, 'newctrl' => 1), array('id' => $trade['tableid']));
                        $gather = pdo_fetch('SELECT sum(num) as num1,count(*) as num2,sum(price*num*100) as tfee,sum(oldprice*num*100)as ofee FROM ' . tablename('j_hmoney_ordergoods') . ' WHERE weid = \'' . $_W['uniacid'] . '\' and orderid=:a ', array(':a' => $trade['id']));
                        $gather2 = pdo_fetch('SELECT sum(a.total_fee) as notfee FROM ' . tablename('j_hmoney_ordergoods') . ' a left join ' . tablename('j_hmoney_goods') . ' b on a.goodid=b.id WHERE a.weid = \'' . $_W['uniacid'] . '\' and b.isnotcoupon=1 and a.out_trade_no=:a ', array(':a' => $trade['out_trade_no']));
                        $data = array('order_fee' => $gather['tfee'], 'total_fee' => $gather['tfee'], 'notdiscount_fee' => $gather2['notfee'], 'num' => $gather['num1'], 'species' => $gather['num2'], 'status' => 1);
                        if ($person != $trade['person']) {
                            $teafee = $person * intval($table['perperson'] * 100) + intval($table['teafee'] * 100);
                            $data['person'] = $person;
                            $data['teafee'] = $teafee;
                        }
                        pdo_update('j_hmoney_order', $data, array('id' => $orderid));
                        if (count($tempInsertAry)) {
                            $insertdata = array('shopid' => $shopid, 'userid' => $userid, 'orderid' => $orderid);
                            if ($isallnew) {
                                $insertdata['mtype'] = 'neworder';
                                $insertdata['message'] = '[' . date('m-d H:i') . '][' . $table['title'] . ']已下单，下单商品种类' . count($newgoodAry) . '，请及时处理。';
                            } else {
                                $insertdata['mtype'] = 'addgood';
                                $insertdata['message'] = '[' . date('m-d H:i') . '][' . $table['title'] . ']加单，加单商品种类' . count($newgoodAry) . '，请及时处理。';
                            }
                            _sendWebMessage($insertdata);
                        }
                        $this->wildDog_socket($shopid);
                        exit(json_encode(array('success' => true)));
                    } else {
                        if ($operation == 'finishgood') {
                            $mid = intval($_GPC['mid']);
                            pdo_update('j_hmoney_ordergoods', array('finishtime' => TIMESTAMP), array('id' => $mid));
                            exit(json_encode(array('success' => true)));
                        } else {
                            if ($operation == 'clearorderid') {
                                isetcookie('selfttableid', '', -1);
                                exit(json_encode(array('success' => true)));
                            } else {
                                if ($operation == 'callsevice') {
                                    $tid = intval($_GPC['tid']);
                                    $txt = trim($_GPC['txt']);
                                    $tablenam = pdo_fetchcolumn('SELECT title FROM ' . tablename('j_hmoney_table') . ' WHERE id=:a ', array(':a' => $tid));
                                    $insertdata = array('shopid' => $shopid, 'userid' => $userid, 'mtype' => 'callsevice', 'message' => '[' . date('m-d H:i') . '][' . $tablenam . ']呼叫服务员：[' . $txt . ']', 'orderid' => $orderid);
                                    _sendWebMessage($insertdata);
                                    exit(json_encode(array('success' => true, 'time' => TIMESTAMP)));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
if ($_GPC['screen']) {
    include $this->template($cfg['floder'] . '/phone/phone2');
} else {
    include $this->template($cfg['floder'] . '/phone/phone');
}